<template>
  <van-pull-refresh
      v-model="freshLoading"
      success-text="刷新成功"
      head-height="100"
      @refresh="onRefresh">
    

    <div class="d-topimg" v-if="(store.loverInfo!=null)">
      在一起{{getsepTime(store.loverInfo.startTime)}}
    </div>

    <div v-for="(item, index) in diarys" :key="item.diaryId"  class="diary-card" @click="toDetial(item.diaryId)">
            <div class="d-info">
              <span style="font-size: 4vw;color: #777;">{{item.username}}</span>
              <span style="font-size: 4vw;font-weight: 600;">{{dateFilter(item.startTime)}}</span>
            </div>
            <div class="d-content">
                <p class="d-p">&nbsp;&nbsp;&nbsp;&nbsp;{{item.diaryContent}}</p>
            </div>
    </div>

    <!-- <div style="height:8vh ;"></div> -->

    <div class="add-diary" @click="writeDiary">
      +
    </div>
  </van-pull-refresh>
</template>
  




<script>
import { showToast,showFailToast } from 'vant';
import axios from 'axios';
import {store} from '../utils/store.js'
import {getTimeSub, getDate} from "../utils/time.js"

  export default {
    name: 'DiaryView',
    activated(){
      store.active="diary"
      this.onLoad()
    },
    data(){
      return{
        store,
        freshLoading: false,
        date: 999,
        diarys: []
      }
    },
    methods:{
      getLover(loverId, userId){
        axios.get("/api/Info/findLover",{
        params:{
          loverId: loverId,
          userId: userId
        }
        }).then((res)=>{
          var result = res.data
          console.log(result)
          if(result.data!=""&&result.data[0]!=null&&result.data[1]!=null){
              store.lover = result.data[0]
              store.loverInfo = result.data[1]
              this.getAllDiary()
          }else{
            showFailToast("请绑定情侣信息")    //没有情侣信息，即情侣id为默认值0，返回到绑定情侣信息界面
            setTimeout(() => {
              this.$router.replace("/pair")
            }, 1000);
          }
          store.queryFlag = true 
        }).catch((error)=>{
          console.log(error)
        })
      },
      getAllDiary(){
        this.diarys = []
        axios.get("/api/Diary/findAllDiary",{
        params:{
          loverId: store.loverInfo.loverId,
        }
        }).then((res)=>{
          console.log(res.data.data)
          let user = store.user.userId
          res.data.data.forEach(element => {
            if(element.userId == user){
              element.username = store.user.username
            }else{element.username = store.lover.username}
            this.diarys.push(element)
          });
          this.freshLoading=false
        }).catch((error)=>{
          console.log(error)
          this.freshLoading=false
        })
      },
      toDetial(diaryId){
        this.$router.push({
            path:  '/detial',
            query: {
              diaryId: diaryId,
              anonymity: 0
            },
          })
        // console.log(diaryId)
        //跳转界面，传递参数diaryid，axios请求
      },
      writeDiary(){
        this.$router.push("/write")
        //跳转界面
      },
      dateFilter(n){
       return getDate(n)
      },
      getsepTime(startTime){
        if(startTime!=""){
          var seperateTime = getTimeSub(Number(startTime), Date.now())
          return seperateTime
        }else{
          return NaN
        }
      },
      onRefresh(){
        axios.get("/api/Info/verifyUser",{   //刷新界面，连带store一起刷新
              params:{
                userPhone: store.userPhone,
                password: store.password
              }
            }).then((res)=>{
              console.log(res.data.data)
              if(res.data.data!=""){
                store.setUser(res.data.data)
                if(res.data.data.loverId!=0){
                  this.getLover(res.data.data.loverId, res.data.data.userId)   
                }else{
                }
              }
            }).catch((error)=>{
              console.log(error)
              showFailToast("后端错误")
            })
      },
      onLoad(){
        if(!store.queryFlag){         
        // store.queryFlag = true   唯一标识，判断是否已经初始化全局store
        store.init(localStorage.getItem("userPhone"),localStorage.getItem("password"))
        if(store.userPhone!=null&&store.password!=null){
            axios.get("/api/Info/verifyUser",{
              params:{
                userPhone: store.userPhone,
                password: store.password
              }
            }).then((res)=>{
              console.log(res.data.data)
              if(res.data.data!=""){
                store.setUser(res.data.data)
                if(res.data.data.loverId!=0){
                  this.getLover(res.data.data.loverId, res.data.data.userId)   // 只有当getLover也成功的时候才算初始化完成store，否则一直保持为false
                }else{
                showFailToast("请绑定情侣信息")    //没有情侣信息，即情侣id为默认值0，返回到绑定情侣信息界面
                setTimeout(() => {
                  this.$router.replace("/pair")
                }, 1000);
                }
              }else{
                showFailToast("请登录或注册")      //数据库中查不到时会返回空，解析为json为即为""
                setTimeout(() => {
                  this.$router.replace("/login")
                }, 1000);
              }
            }).catch((error)=>{
              console.log(error)
              showFailToast("后端错误")
            })
        }else{
          showFailToast("请登录或注册")     //没有本地缓存，请登录或注册
          setTimeout(() => {
            this.$router.replace("/login")
          }, 1000);
        }
      }
      }
    }
  }
</script>

<style>
.d-p{
    overflow: hidden;
    text-overflow:ellipsis;
    -webkit-line-clamp: 3;
    word-wrap: break-word;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    /* line-height: 4vw; */

}

.d-topimg{
  width: 100%;
  height: 54vw;
  /* background-image: url(../assets/d-topimg.png); */
  background-size: 100% 100%;
  background-color: #f9cdd4;
  border-bottom-left-radius: 10vw;
  border-bottom-right-radius: 10vW;
  line-height: 54vw;
  font-size: 5vw;
  font-weight: 600;
  margin-bottom: -15vw;
}

.diary-card{
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 3vw;
  margin: 4vw 4vw;
  padding: 2vw;
  text-align: left;
}

.add-diary{
  position: fixed;
  bottom: 16vw;
  right: 3vw;
  width: 60px;
  height: 60px;
  background-color: #f9cdd4;
  border-radius: 50%;
  font-size: 46px;
  color: rgb(132, 132, 132);
  line-height: 60px;
}



</style>

